package be.phl.mycinema.classes;

import java.io.IOException;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.util.Log;
import be.phl.mycinema.Utils;

import com.google.gson.Gson;

public class ReadJsonTask<T> extends AsyncTask<String, Void, ArrayList<T>> {

	private Activity a;
	private String tag;
	private Type collectionType;
	
	public ReadJsonTask(Activity a,String tag, Type collectionType) {
		this.a = a;
		this.tag = tag;
		this.collectionType = collectionType;
	}
	
	@Override
	protected ArrayList<T> doInBackground(String... params) {
		if (Utils.isNetworkAvailable((ConnectivityManager) a.getSystemService(Context.CONNECTIVITY_SERVICE))) {
			try {
				URL url = new URL(params[0]);
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				Log.d(tag, "Connection opened..");

				Gson g = new Gson();

				Log.d(tag, "Reading json..");
				String json = Utils.readJsonFromServer(connection.getInputStream());
				
				ArrayList<T> films = g.fromJson(json, collectionType);

				Log.d(tag, "Async task succesfull!");
				return films;
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	@Override
	protected void onCancelled() {
		cancel(true);
	}
}
